package com.wkg.music_player.controller;

import com.wkg.music_player.mapper.LoveMusicMapper;
import com.wkg.music_player.mapper.MusicMapper;
import com.wkg.music_player.model.Music;
import com.wkg.music_player.model.User;
import com.wkg.music_player.tools.Constant;
import com.wkg.music_player.tools.ResponseBodyMessage;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOError;
import java.io.IOException;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/music")
public class MusciController {
    @Autowired
    private LoveMusicMapper loveMusicMapper;

    @Value("${music.local.path}")
    private String SAVE_PATH;

    @Autowired
    private MusicMapper musicMapper;

    @RequestMapping("/upload")
    public ResponseBodyMessage<Boolean> insertMusic(@RequestParam String singer,
                                                    @RequestParam("filename") MultipartFile file,
                                                    HttpServletRequest request,
                                                    HttpServletResponse resp) {
        //1.是否登录
        log.info("singer: "+singer);
        log.info("file:" + file.getOriginalFilename());
        HttpSession httpSession = request.getSession(false);
        if (httpSession == null || httpSession.getAttribute(Constant.USERINFO_SESSION_KEY) == null) {
            System.out.println("没有登录");
            return new ResponseBodyMessage<>(-1, "请登录上传", false);
        }

        String fileNameAndType = file.getOriginalFilename();
        int index = fileNameAndType.lastIndexOf(".");
        String title = fileNameAndType.substring(0, index);
        //查询当前数据库是否有此歌曲
        Music music = musicMapper.selectByOne(title, singer);
        if (music != null) {
            return new ResponseBodyMessage<>(-1, "音乐已上传过,禁止重复上传", false);
        }

        //2.上传到服务器

        System.out.println("fileNameAndType:" + fileNameAndType);

        String path = SAVE_PATH + fileNameAndType;
        File dest = new File(path);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
            //return new ResponseBodyMessage<>(0, "上传成功", true);
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseBodyMessage<>(-1, "服务器上传失败", false);
        }

        //进行数据库的上传
        //1.准备数据  2.调用insert

        User user = (User) httpSession.getAttribute(Constant.USERINFO_SESSION_KEY);
        int userid = user.getId();

        //1.播放音乐 http请求
        //String url = "/music?path=" + title;
        String url = "/music/get?path=" + title; // 包含.mp3

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String time = simpleDateFormat.format(new Date());

        try {
            int count = musicMapper.insert(title, singer, time, url, userid);
            if (count == 1) {
                resp.sendRedirect("/list.html");
                return new ResponseBodyMessage<>(0, "音乐上传成功!", true);
            }
            return new ResponseBodyMessage<>(-1, "上传音乐到数据库失败", false);
        } catch (Exception e) {
            e.printStackTrace();
            dest.delete();
            return new ResponseBodyMessage<>(-1, "上传音乐到数据库失败", false);
        }
    }

    //播放音乐的时候: /music/get?path=xxx.mp3
    @RequestMapping("/get")
    public ResponseEntity<byte[]> func(String path) {
        if (path == null || path.isEmpty()) {
            return ResponseEntity.badRequest().build();
        }
        File file = new File(SAVE_PATH + path);
        byte[] a = null;
        try {
            a = Files.readAllBytes(file.toPath());
            if (a == null) {
                return ResponseEntity.badRequest().build();
            }
            return ResponseEntity.ok(a);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ResponseEntity.badRequest().build();
    }

    //删除单个音乐
    @RequestMapping("/delete")
    public ResponseBodyMessage<Boolean> deleteMusicById(@RequestParam String id) {
        //1.先检查这个音乐是否存在
        int musicId = Integer.parseInt(id);
        //2.如果存在要进行删除
        Music music = musicMapper.selectById(musicId);
        if (music == null) {
            System.out.println("没有这个id的音乐!");
            return new ResponseBodyMessage<>(-1, "没有您要删除的音乐", false);
        }
        //3.删除数据库
        int count = musicMapper.deleteById(musicId);
        if (count != 1) {
            System.out.println("数据库删除这个id的音乐失败!");
            return new ResponseBodyMessage<>(-1, "数据库删除这个id的音乐失败!", false);
        }
        //4.删除服务器的数据
        /*int index = music.getUrl().lastIndexOf("=");
        String fileName = music.getUrl().substring(index + 1);*/

        // 修改后（直接取存储的文件名）
        String fileName = music.getUrl().split("=")[1]; // 直接获取"周杰伦-晴天.mp3"

        File file = new File(SAVE_PATH + fileName + ".mp3");
        System.out.println("当前路径:" + file);

        if (!file.delete()) {
            return new ResponseBodyMessage<>(-1, "服务器删除这个id的音乐失败!", false);
        }
        //删除用户收藏中的数据库音乐id
        int ret = loveMusicMapper.deleteLoveMusicByMusicId(musicId);
        if (ret != 1) {
            System.out.println("用户收藏表中的音乐id删除失败!");
            return new ResponseBodyMessage<>(-1, "用户收藏表中的音乐id删除失败!", false);
        }
        return new ResponseBodyMessage<>(0, "音乐删除成功!", true);
    }

    @RequestMapping("/deleteSel")
    public ResponseBodyMessage<Boolean> deleteSelMusic(@RequestParam("id[]") List<Integer> id) {
        System.out.println("所有的id:" + id);
        int sum = 0;
        for (int i = 0; i < id.size(); i++) {
            Music music = musicMapper.selectById(id.get(i));
            if (music == null) {
                System.out.println("没有这个id的音乐!");
                return new ResponseBodyMessage<>(-1, "没有您要删除的音乐 id:" + id.get(i), false);
            }
            int ret = musicMapper.deleteById(id.get(i));
            if (ret != 1) {
                System.out.println("数据库删除这个id的音乐失败!");
                return new ResponseBodyMessage<>(-1, "数据库删除这个id的音乐失败! id:" + id.get(i), false);
            }
            //4.删除服务器的数据
            int index = music.getUrl().lastIndexOf("=");
            String fileName = music.getUrl().substring(index + 1);

            File file = new File(SAVE_PATH + fileName + ".mp3");
            System.out.println("当前路径:" + file);

            if (!file.delete()) {
                return new ResponseBodyMessage<>(-1, "服务器删除这个id的音乐失败!id:" + id.get(i), false);
            }
            //删除用户收藏中的数据库音乐id
            // 这个音乐不一定在你的收藏列表中,如果不在返回受影响的行数就是0  这里逻辑有点问题
            int count = loveMusicMapper.deleteLoveMusicByMusicId(id.get(i));
            /*if (count != 1) {
                // 返回0 就直接return了  就不会删除 后面的音乐了
                System.out.println("用户收藏表中的音乐id删除失败!");
                return new ResponseBodyMessage<>(-1, "用户收藏表中的音乐id删除失败!", false);
            }*/

            sum += ret;
        }

        if (sum != id.size()) {
            return new ResponseBodyMessage<>(-1, "批量删除音乐失败!", false);
        }
        System.out.println("批量删除成功!");
        return new ResponseBodyMessage<>(0, "音乐删除成功!", true);
    }

    @RequestMapping("/findmusic")
    public ResponseBodyMessage<List<Music>> findmusic(@RequestParam(required = false) String musicName) {
        List<Music> musicByName = null;
        try {
            if (musicName != null) {
                musicByName = musicMapper.findMusicByName(musicName);
            } else {
                musicByName = musicMapper.findMusic();
            }
            return new ResponseBodyMessage<>(0, "音乐查询成功!", musicByName);
        } catch (Exception e) {
            System.out.println("音乐查询是失败!");
            return new ResponseBodyMessage<>(-1, "音乐查询失败!", musicByName);
        }


    }

}
